using UnityEngine;
using UnityEditor;

[CustomPropertyDrawer(typeof(SceneNameAttribute))]
public class SceneNameDrawer : PropertyDrawer
{
    int sceneIndex = -1;
    GUIContent[] sceneNames;
    private readonly string[] sceneNameDispose = { "Assets/Scenes/", ".unity" };
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        if (EditorBuildSettings.scenes.Length == 0)
        {
            return;
        }
        if (sceneIndex == -1)
        {
            GetSceneNameArray(property);
        }

        int oldIntex = sceneIndex;

        sceneIndex = EditorGUI.Popup(position, label, sceneIndex, sceneNames);

        if (oldIntex != sceneIndex)
        {
            property.stringValue = sceneNames[sceneIndex].text;
        }
    }


    private void GetSceneNameArray(SerializedProperty property)
    {
        var scenes = EditorBuildSettings.scenes;

        sceneNames = new GUIContent[scenes.Length];

        for (int i = 0; i < scenes.Length; i++)
        {
            var sceneName = scenes[i].path;
            for (int j = 0; j < sceneNameDispose.Length; j++)
            {
                sceneName = sceneName.Replace(sceneNameDispose[j], "");
            }

            if (string.IsNullOrEmpty(sceneName))
            {
                sceneName = "[Delete Scene]";
            }

            sceneNames[i] = new GUIContent(sceneName);
        }

        if (sceneNames.Length == 0)
        {
            sceneNames = new GUIContent[] { new GUIContent("[No Scene]") };
        }

        if (string.IsNullOrEmpty(property.stringValue))
        {
            sceneIndex = 0;
        }
        else
        {
            bool nameFound = false;
            for (int i = 0; i < sceneNames.Length; i++)
            {
                int index = i;
                if (sceneNames[index].text == property.stringValue)
                {
                    sceneIndex = index;
                    nameFound = true;
                    break;
                }
            }

            if (!nameFound)
            {
                sceneIndex = 0;
            }
        }

        property.stringValue = sceneNames[sceneIndex].text;
    }
}
